package com.hawk.eye.client.tracer;

import com.hawk.eye.client.toolkit.LogPropertyHolder;
import com.hawk.eye.client.toolkit.TraceIdGenerator;
import com.hawk.eye.common.utils.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.env.Environment;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @className: TrackerFilter
 * @description: 负责增加Trace属性的过滤器
 * @author: salad
 * @date: 2023/1/9
 **/
@Slf4j
@AllArgsConstructor
public class TrackerFilter extends OncePerRequestFilter {

    private final TraceIdGenerator traceIdGenerator;

    private final Environment environment;

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 使用 重写 HttpServletRequestWrapper 的自定义包装类
//        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        // 使用 重写 HttpServletResponseWrapper 的自定义包装类
//        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
        // 只能执行一次获取流方法
        try {
            // 获取传参
//            String requestParamJson = new String(requestWrapper.getBody());
//            String partsAsString = requestWrapper.getMultiPartsAsString();
//            LogPropertyHolder.puts("requestTime,requestParams,requestMultiParts",
//                    DATETIME_FORMATTER.format(LocalDateTime.now()), requestParamJson, partsAsString);
//            LogPropertyHolder.puts("requestTime", DATETIME_FORMATTER.format(LocalDateTime.now()));
            // 具体方法执行流程
            String tid = request.getHeader("tid");
            String entranceUri = request.getHeader("entranceUri");
            if (StringUtil.isBlank(tid)) {
                tid = traceIdGenerator.generate();
            }
            LogPropertyHolder.puts("serviceName,entranceUri,requestUri,tid",
                    environment.getProperty("spring.application.name"), entranceUri, request.getRequestURI(), tid);
            MDC.put("name", "测试");
            chain.doFilter(request, response);
//             触发获取流操作后，可以从缓存多次拿数据
//            String respDataJson = new String(responseWrapper.toByteArray());
//            LogPropertyHolder.puts("responseResult", respDataJson);
            // 需要重新写入内容，否则流无输出内容
//            outputStream.write(respDataJson.getBytes(StandardCharsets.UTF_8));
//            outputStream.flush();
        } finally {
            LogPropertyHolder.removes("serviceName,entranceUri,requestUri,tid");
        }

    }


}